#define DEBUG

#include <Arduino.h>
#include "led_driver.h"
#include "bluetooth_serial.h"
#include "ttl_serial.h"
#include "effects.h"
#include "ir_remote.h"
#include "ir_command_handler.h"

// 蓝牙设备名称
const char *btDeviceName = "ESP32_RGB_LED"; // 蓝牙设备名称

// 系统组件实例
LEDDriver ledDriver;
BluetoothSerial btSerial;
TTLSerial ttlSerial;
IRRemote irRemote;

// 效果实例
StaticColorEffect staticEffect(0, 255, 0);  // 绿色静态效果
BreathingEffect breathingEffect(0, 0, 255); // 蓝色呼吸效果

BaseEffect* currentEffect = &staticEffect;
int currentEffectIndex = 0;
const int effectCount = 2;

// 系统状态
bool systemRunning = false;

// 任务句柄
TaskHandle_t bluetoothTaskHandle = NULL;
TaskHandle_t ledTaskHandle = NULL;

// 蓝牙任务函数
void bluetoothTask(void* parameter);

// LED调光任务函数
void ledTask(void* parameter);

// 初始化函数
void setup() {
    // 初始化串口
    ttlSerial.begin(115200);
    ttlSerial.println("System starting...");
    
    // 初始化红外遥控
    irRemote.begin();
    ttlSerial.println("IR remote initialized");
    
    // 初始化LED驱动
    ledDriver.init();
    ttlSerial.println("LED driver initialized");
    
    // 初始化当前效果
    currentEffect->init(&ledDriver);
    systemRunning = true;
    
    // 创建蓝牙任务并绑定到CPU 0
    xTaskCreatePinnedToCore(
        bluetoothTask, 
        "BluetoothTask", 
        4096, 
        NULL, 
        1, 
        &bluetoothTaskHandle, 
        0);
    
    // 创建LED调光任务并绑定到CPU 1
    xTaskCreatePinnedToCore(
        ledTask, 
        "LedTask", 
        2048, 
        NULL, 
        2, 
        &ledTaskHandle, 
        1);
    
    ttlSerial.println("System initialized");
}

// 处理串口命令
void handleSerialCommands();

// 处理红外命令
void handleIRCommands();

// 处理命令
void processCommand(char command);

// 蓝牙任务函数
void bluetoothTask(void* parameter) {
    // 初始化蓝牙
    btSerial.begin("ESP32_RGB_LED");
    ttlSerial.println("Bluetooth initialized with name: ESP32_RGB_LED");
    btSerial.println("Bluetooth initialized with name: ESP32_RGB_LED");
    
    // 蓝牙任务主循环
    while (true) {
        // 处理蓝牙串口数据
        while (btSerial.available()) {
            char c = btSerial.read();
            processCommand(c);
        }
        
        // 小延迟以控制更新频率
        delay(50);
    }
}

// LED调光任务函数
void ledTask(void* parameter) {
    // LED调光任务主循环
    while (true) {
        // 更新当前效果
        if (systemRunning && currentEffect) {
            currentEffect->update();
        }
        
        // 小延迟以控制更新频率
        delay(10);
    }
}

// 主循环
void loop() {
    // 处理串口命令
    handleSerialCommands();
    
    // 处理红外命令
    handleIRCommands();
    
    // 主循环中不再处理LED更新，避免延迟干扰
    // LED更新由独立的ledTask处理
    
    // 小延迟以控制更新频率
    delay(50);
}

// 处理串口命令
void handleSerialCommands() {
    // 检查TTL串口数据
    while (ttlSerial.available()) {
        char c = ttlSerial.read();
        processCommand(c);
    }
    
    // 检查蓝牙串口数据
    if (btSerial.isConnected()) {
        while (btSerial.available()) {
            char c = btSerial.read();
            processCommand(c);
        }
    }
}

// 处理红外命令
void handleIRCommands() {
    if (irRemote.available()) {
        uint32_t command = irRemote.readCommand();
        ttlSerial.print("IR Command received: 0x");
        // 转换为十六进制字符串
        char hexStr[9];
        sprintf(hexStr, "%08X", command);
        ttlSerial.println(hexStr);
        if (btSerial.isConnected()) {
            btSerial.print("IR Command received: 0x");
            btSerial.println(hexStr);
        }
        
        // 处理红外命令
        handleIRCommand(command, ledDriver, currentEffect, currentEffectIndex, 
                       systemRunning, ttlSerial, btSerial);
    }
}

// 处理命令
void processCommand(char command) {
    switch (command) {
        case '0':
            // 切换到静态效果
            currentEffectIndex = 0;
            currentEffect = &staticEffect;
            currentEffect->init(&ledDriver);
            ttlSerial.println("Switched to Static Color effect");
            if (btSerial.isConnected()) {
                btSerial.println("Switched to Static Color effect");
            }
            break;
            
        case '1':
            // 切换到呼吸效果
            currentEffectIndex = 1;
            currentEffect = &breathingEffect;
            currentEffect->init(&ledDriver);
            ttlSerial.println("Switched to Breathing effect");
            if (btSerial.isConnected()) {
                btSerial.println("Switched to Breathing effect");
            }
            break;
            
        case 'n':
        case 'N':
            // 切换到下一个效果
            currentEffectIndex = (currentEffectIndex + 1) % effectCount;
            switch (currentEffectIndex) {
                case 0:
                    currentEffect = &staticEffect;
                    break;
                case 1:
                    currentEffect = &breathingEffect;
                    break;
            }
            currentEffect->init(&ledDriver);
            ttlSerial.print("Switched to effect: ");
            ttlSerial.println(currentEffect->getName());
            if (btSerial.isConnected()) {
                btSerial.print("Switched to effect: ");
                btSerial.println(currentEffect->getName());
            }
            break;
            
        case 's':
        case 'S':
            // 切换系统运行状态
            systemRunning = !systemRunning;
            if (systemRunning) {
                ttlSerial.println("System started");
                if (btSerial.isConnected()) {
                    btSerial.println("System started");
                }
            } else {
                // 清除LED
                ledDriver.clear();
                ttlSerial.println("System stopped");
                if (btSerial.isConnected()) {
                    btSerial.println("System stopped");
                }
            }
            break;
            
        default:
            // 未知命令
            ttlSerial.println("Unknown command. Available commands:");
            ttlSerial.println("0 - Static Color effect");
            ttlSerial.println("1 - Breathing effect");
            ttlSerial.println("n - Next effect");
            ttlSerial.println("s - Start/Stop system");
            break;
    }
}